<?php

namespace app\wechat\controlle\customer;

use app\wechat\controller\Openid;
use app\wechat\controller\Platform;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\Kernel\Messages\Text;
use Pheanstalk\Pheanstalk;

// 客服消息相关
class Deanstalk
{
    public $ser;
    public $platform;
    public $openid_redis;

    // 初始化操作
    public function __construct()
    {
        $this->ser = new Pheanstalk('127.0.0.1');
        $this->platform = new Platform();
        $this->openid_redis = new Openid(true);
        set_time_limit(0);
    }

    // 处理图文消息
    public function handle_msg($item, $type)
    {
        if ($type == "news") {
            $new = [
                new NewsItem([
                    'title' => $item['title'],
                    'description' => '',
                    'url' => $item['url'],
                    'image' => $item['image'],
                ]),
            ];
            return new News($new);
        } elseif ($type == "text") {
            return new Text($item['content']);
        }
    }

    // 开启服务
    public function start()
    {
        echo 'start';
        while (1) {
            // 监听send管道
            $job = $this->ser->watch('customer')->ignore('default')->reserve();
            // 获取任务数据
            $data = json_decode($job->getData(), true);

            $appid = $data['appid'];
            if ($appid != '') {
                try {
                    $type = $data['type'];
                    $item = $data['item'];
                    $refresh_token = $data['refresh_token'];

                    $gh = $this->platform->getGhWithToken($appid, $refresh_token);

                    $msg = $this->handle_msg($item, $type);

                    // 循环发送
                    $openid = $this->openid_redis->pop_openid($appid);
                    while ($openid) {
                        $result = $gh->customer_service->message($msg)->to($openid)->send();
                        if ($result['errcode'] == 0) {
                            $this->openid_redis->count($appid, $openid);
                        }
                        $openid = $this->openid_redis->pop_openid($appid);
                    }
                } catch (HttpException $exception) {
                }
            }

            // 删除任务
            $this->ser->delete($job);
            usleep(100);
        }
    }

}

$service = new Deanstalk();
$service->start();
